<template>
  <div class="w-h-100">
    <el-tabs type="border-card" v-model="activeName">

      <el-tab-pane name="uploadWorks" label="上传作品">
        <div>
          <span class="line"></span>
          <span>基本信息</span>
          <div class="form-box">
            <el-form inline :model="userInfo" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
              <el-form-item label="我的姓名" prop="username">
                <el-input v-model="userInfo.username" disabled clearable size="mini" style="width: 160px"></el-input>
              </el-form-item>
              <el-form-item label="所在学校" prop="schoolName">
                <el-select v-model="userInfo.schoolName" disabled placeholder="请选择所在学校" clearable filterable
                           size="mini"
                           style="width: 160px">
                  <el-option :label="item.schoolName" :key="item.index" :value="item.schoolName"
                             v-for="(item ,index) in schooldOption"></el-option>
                </el-select>
              </el-form-item>
              <br>
              <el-form-item label="所在年级" prop="gradeName">
                <el-select v-model="userInfo.gradeId" disabled placeholder="请选择所在年纪" clearable filterable
                           size="mini"
                           style="width: 160px">
                  <el-option :label="item.gradeName" :value="item.gradeId" v-for="item in gradeDicc"
                             :key="item.gradeId"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="所在班级" prop="classesId">
                <el-select v-model="userInfo.classesId" disabled placeholder="请选择所在班级" clearable filterable
                           size="mini"
                           style="width: 160px">
                  <el-option :label="item.classesName" :value="item.classesId" :key="item.classesId"
                             v-for="item in classOption"></el-option>
                </el-select>
              </el-form-item>
              <br>
              <el-form-item label="指导老师" prop="teacherName">
                <el-input v-model="userInfo.teacherName" size="mini" clearable style="width: 160px"></el-input>
              </el-form-item>
              <el-form-item label="学生电话" prop="telephone">
                <el-input v-model="userInfo.telephone" disabled type="number" clearable size="mini"
                          style="width: 160px"></el-input>
              </el-form-item>
              <el-divider></el-divider>
              <br>
              <el-form-item label="作品类别" prop="categoryArr">
                <el-cascader v-model="userInfo.categoryArr" :options="options" size="mini" clearable
                             class="zplb"
                             placeholder="请选择作品类别"></el-cascader>
              </el-form-item>

              <el-form-item label="作品名称" prop="tutorialName">
                <el-input v-model="userInfo.tutorialName" size="mini" clearable style="width: 160px"></el-input>
              </el-form-item>
              <br>
              <el-form-item label="作品内容" prop="tutorialIntroduct">
                <el-input type="textarea" v-model="userInfo.tutorialIntroduct" size="mini"
                          class="textareaBox" clearable></el-input>
              </el-form-item>
              <br>
              <el-form-item label="上传作品" prop="fileVideo">
                <span
                    style="color: rgb(128,128,128);font-size: 10px">只能上传mp4文件，且不超过500M，超出限制的视频无法上传</span>
                <br>
                <input type="file" style="display: none" id="file" ref="uploadVideo" accept="video/*"
                       @change="uploadVideoClick($event)"/>
                <canvas ref="canvas" style="display: none;"></canvas>
                <el-button type="primary" size="mini" @click="getFile">重新上传</el-button>
                <i class="el-icon-document" style="margin:0 20px"></i>
                <el-tag
                    closable
                    type="info" @close="removeVideo" v-if="userInfo.fileName">
                  <span style="color: rgb(128,128,128);font-size: 13px">{{ userInfo.fileName }}</span>
                </el-tag>
                <!--                进度条-->
                <div v-if="percenFlag">
                  <el-row>
                    <el-col :span="20">
                      <el-progress :percentage="percentageValue"></el-progress>
                    </el-col>
                    <el-col :span="1">
                      <el-button type="danger" icon="el-icon-delete" circle @click="closeClick" size="mini">
                      </el-button>
                    </el-col>
                  </el-row>
                </div>
              </el-form-item>
              <br>
              <el-form-item label="作品封面" prop="coverImg">
                <span style="color: rgb(128,128,128);font-size: 10px">已从视频中选择了1张推荐封面，也可自行上传</span>
                <br>
                <el-upload
                    ref="uploadCover"
                    action="#"
                    :show-file-list="false"
                    :http-request="uploadCoverClick"
                    list-type="picture-card"
                >
                  <i class="el-icon-plus"></i>
                </el-upload>
                <div style="position: absolute;top: 35%;left: 60%">
                  <el-image
                      :src="userInfo.coverImg" fit="contain "
                      style="width: 78px; height: 78px">
                    <div slot="placeholder">
                      加载中
                      <i class="el-icon-loading"></i>
                    </div>
                  </el-image>
                </div>
              </el-form-item>
              <br>
              <el-form-item>
                <!--                style="margin-left: calc(100% - 10px)"-->
                <el-button :loading="submitLoad" type="primary" @click="submitForm('ruleForm')">
                  上传视频
                </el-button>
              </el-form-item>
            </el-form>

          </div>
        </div>
      </el-tab-pane>
      <el-tab-pane name="myWorks" label="我的作品">
        <!--        作品列表-->
        <div v-if="showList">
          <el-row type="flex" v-for="(item,index) in worksList" :key="index" class="markItem" @click="rowClick(item)">
            <el-col :span="2" style="min-width: 167px;width: 167px;margin-top:24px">
              <div @click="detailsClick(item)">
                <el-image
                    style="width: 134px; height: 96px;"
                    :src="item.coverImg"
                    fit="contain"></el-image>
              </div>

            </el-col>
            <el-col :span="22" style="margin-top:24px">
              <div @click="detailsClick(item)">
                <el-row>
                  <el-col :span="18">
                    <div style="font-size:14px;color: #333333;margin-bottom: 10px">{{ item.tutorialName }}</div>
                    <div>
                  <span style="font-size:12px;color: #666666;padding-top: 5px;margin: 4px 0">{{
                      '学生：' + item.nickName
                    }}</span>
                      <span
                          style="font-size:12px;color: #666666;padding-top: 5px;margin-left: 18px;">{{
                          '指导老师：' + item.videoInstructor
                        }}</span>
                    </div>
                    <!--                  评分-->
                    <el-rate v-model="item.videoScore"
                             :show-score="true"
                             disabled
                             text-color="#ff9900"
                             style="margin: 2px 0"
                             allow-half
                             :score-template="item.number"
                    ></el-rate>
                  </el-col>
                  <el-col :span="6">
                    <div class="updateBox" @click.stop="">
                      <el-button circle type="primary" class="el-button-custom" style="margin-right: 10px"
                                 @click.stop="updateObjClick(item)">改
                      </el-button>
                      <el-popconfirm @click.prevent @click.stop @confirm="deleteClick(item.id)"
                                     onConfirm={confirm}
                                     title="删除后将无法访问此视频，确定删除？"
                      >
                        <el-button slot="reference" class="el-button-custom" circle icon="el-icon-delete"></el-button>
                      </el-popconfirm>
                    </div>
                  </el-col>
                </el-row>
                <el-row>
                  <div style="font-size:12px;color: #666666;text-overflow:ellipsis;margin: 4px 0">{{
                      item.videoEvaluation ? item.videoEvaluation : "暂无评语"
                    }}
                  </div>
                </el-row>
              </div>
            </el-col>
          </el-row>
        </div>
        <!--        作品详情-->
        <div v-else style="width: 888px">
          <el-row>
            <el-button @click="showList=true" type="primary" size="small">返回列表</el-button>
            <!--            视频展示-->
            <div class="desc-box">
              <video controls class="w-h-100" :src="works.videoUrl"></video>
            </div>
            <!--            文案展示-->
            <div>
              <div style="font-size:25px;font-weight:bold;color: #333333;margin: 10px 0">{{
                  works.tutorialName ? works.tutorialName : "暂无比赛名称"
                }}
              </div>
              <div>
                  <span class="student-teacher">学生：{{
                      works.nickName ? works.nickName : "暂无学生姓名"
                    }}</span>
                <span class="student-teacher"
                      style="margin-left: 18px;">指导老师：{{
                    works.videoInstructor ? works.videoInstructor : "暂无指导老师"
                  }}</span>
              </div>
              <!--              作品评分-->
              <el-rate v-model="works.videoScore"
                       show-score
                       disabled
                       text-color="#ff9900"
                       style="margin: 2px 0"
                       :score-template="works.number"
              ></el-rate>
              <div class="worksCon">{{
                  '作品内容：' + works.tutorialIntroduct ? works.tutorialIntroduct : "暂无作品内容"
                }}
              </div>
              <el-divider/>
              <div style="margin-top: 40px;margin-bottom: 20px"><span>作品评语:</span></div>
              <div style="font-size:12px;color: #666666;">{{
                  works.videoEvaluation ? works.videoEvaluation : "暂无评语"
                }}
              </div>
            </div>
          </el-row>
        </div>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import {getStudentInfo, getUpToken, getVideolListById, remove, uploadCover, uploadStudentCover} from "@/api/request";
import {classOption, diccArr, gradeDicc, schooldOption, worksOptions} from "@/utils/dicc";
import {meassageError, meassageSuccess, meassageWarning} from "@/utils";
import {dataURLtoFile} from "@/utils/hook";


export default {
  name: 'index',
  data() {
    return {
      subscriptionObj: null,//七牛云上传的对象
      percentageValue: 0,//进度条数值
      percenFlag: false,
      submitLoad: false,
      gradeDicc,
      schooldOption,
      classOption,
      activeName: 'uploadWorks',
      showList: true,
      worksType: '',
      works: {
        coverImg: "",
        tutorialName: "",//作品名称
        nickName: "",//学生姓名
        videoInstructor: "",
        videoEvaluation: "",//评语
        number: '',//分数
        tutorialIntroduct: "",//作品内容
        videoUrl: "",
        videoScore: ''//星星
      },
      worksList: [
        // {
        //   coverImg: "",
        //   tutorialName: "",
        //   nickName: "",
        //   videoInstructor: "",
        //   videoEvaluation: "",
        //   number: '10分',
        //   worksContent: "",
        //   videoScore: 2.6,
        //   videoUrl: ""
        // }
      ],
      dialogVisible: false,
      rules: {
        username: [{required: true, message: '请输入姓名', trigger: 'blur'},],
        schoolName: [{required: true, message: '请输入所在学校', trigger: 'blur'},],
        gradeId: [{required: true, message: '请输入所在年纪', trigger: 'blur'},],
        classesId: [{required: true, message: '请输入所在班级', trigger: 'blur'},],
        teacherName: [{required: true, message: '请输入指导老师姓名', trigger: 'blur'},],
        telephone: [{required: true, message: '请输入手机号码', trigger: 'blur'},],
        categoryArr: [{required: true, message: '请选择作品类别', trigger: 'blur'},],
        tutorialName: [{required: true, message: '请输入作品名称', trigger: 'blur'},],
        tutorialIntroduct: [{required: true, message: '请输入作品内容', trigger: 'blur'},],
        fileVideo: [{required: true, message: '请上传作品', trigger: 'blur'},],
        coverImg: [{required: true, message: '请上传作品封面', trigger: 'blur'},],
      },
      addOrUpdateFlag: true,//判断是新增还是修改。true为新增，false为修改/默认是新增
      userInfo: {
        fileVideo: '',
        fileName: '',
        username: "",
        realname: "",
        studentLd: null,
        studentNo: "",
        telephone: "",
        sex: null,
        regionProvinceCode: "",
        regionProvinceName: "",
        regionCityCode: '',
        regionCityName: "",
        regionDistrictId: '',
        regionDistrictName: "",
        schoolName: "",
        gradeId: "",
        gradeName: "",
        classesId: null,
        classesName: null,
        classesId2: null,
        classesName2: null,
        teacherId: null,
        teacherName: "",
        parentName: null,
        //学生考试报名号
        examStudentId: '',
        //竞赛ID
        examId: '',
        //竞赛名称
        examName: '',
        //作品名称
        tutorialName: '',
        //阶段ID
        stageDetailId: '',
        //作品分类数组
        categoryArr: [],
        //一级视频分类Id
        categoryId: '',
        //一级视频分类名称
        categoryName: '',
        //二级视频分类Id
        subjectId: '',
        //二级视频分类名称
        subjectName: '',
        //视频内容
        tutorialIntroduct: '',
        //视频链接
        videoUrl: '',
        //学生视频id，用于修改功能使用，传递该参数表明本次为修改操作
        id: '',
        //封面URL
        coverImg: ''
      },
      options: worksOptions,
      diccArr

      //纷纷
    };
  },
  methods: {
    //取消上传
    closeClick() {
      this.percentageValue = 0
      this.subscriptionObj.unsubscribe()
      this.userInfo.fileName = ''
      this.percenFlag = false
    },
    //移除视频
    removeVideo() {
      this.userInfo.fileName = ''
      this.userInfo.coverImg = ''
    },
    // 点击上传文件触发input文件
    getFile() {
      this.$refs.uploadVideo.click()
    },
    //上传视频
    uploadVideoClick(e) {
      // debugger
      const fileDom = document.getElementById("file"); // js 获取文件对象
      const fileObj = fileDom.files
      let file = fileObj[0];
      let fileSize = 0;
      if (file) {
        fileSize = file.size;
        if (fileSize > 1024 * 1024 * 512) { // 1GB in bytes
          return meassageWarning('文件大小不能超过500M');
        }
        if (file.type !== 'video/mp4') { // Check if the file is MP4
          return meassageWarning('请上传MP4格式的文件');
        }

        if (file.name.includes(".mp4")) {
          this.userInfo.fileName = file.name//获取保存文件名称
        } else {
          this.userInfo.fileName = file.name + ".mp4"//获取保存文件名称
        }

        //截图第一帧转成/png图片
        const video = document.createElement('video');
        const canvas = this.$refs.canvas;
        const context = canvas.getContext('2d');

        video.src = URL.createObjectURL(file);
        video.addEventListener('loadedmetadata', () => {
          video.currentTime = 0; // 设置视频当前时间为第0秒
          video.addEventListener('seeked', () => {
            canvas.width = video.videoWidth;
            canvas.height = video.videoHeight;
            context.drawImage(video, 0, 0, canvas.width, canvas.height);
            //base64转Blob
            // this.userInfo.coverImg = canvas.toDataURL('image/jpeg')
            const imgFile = dataURLtoFile(canvas.toDataURL('image/jpeg'))
            //上传封面
            const formData = new FormData()
            formData.append('file', imgFile) // 传入bpmn文件
            uploadCover(formData).then(res => {
              if (res.code === 200) {
                this.userInfo.coverImg = res.dataMap.url
                // meassageSuccess(res.msg)
              } else {
                meassageError(res.msg)
              }
            })
          });
        })
        this.percenFlag = true//打开进度条
        const that = this
        //七牛云配置项②
        const observer = {
          next(res) {
            // 用于展示上传进度
            console.log("七牛运next", res)
            //计算进度条数值
            that.percentageValue = parseInt(res.total.percent)
          },
          error(err) {
            meassageError("上传失败")
            that.percentageValue = 0//恢复默认值
            that.percenFlag = false;//上传失败，关闭进度条
            console.log("七牛运next", err)
          },

          complete(res) {
            that.percenFlag = false;//上传完成，关闭进度条
            that.percentageValue = 0//恢复默认值
            console.log("七牛云complete", res)
            meassageSuccess("上传成功")
            that.userInfo.videoUrl = "https://file.sycup.top/" + res.key//videoUrl
            that.userInfo.fileVideo = res.hash//保存hash值
          }
        }
        //七牛云配置项①
        const config = {
          useCdnDomain: true,
          region: null,    // 根据地区不同，官网有不同的配置
          concurrentRequestLimit: 1000,
        }
        //设置文件的配置③
        const putExtra = {
          fname: "",
          params: {},
          mimeType: null
        };
        const key = "vod/" + this.userInfo.id + "/" + file.name  //上传文件加入用户id前缀
        getUpToken().then(res => {
          if (res.code === 200) {
            const token = res.data
            const observable = this.$qiniu.upload(file, key, token, putExtra, config)
            // 上传开始
            this.subscriptionObj = observable.subscribe(observer)
          }
        })
      } else {
        meassageWarning('请选择一个文件');
      }
      e.target.value = '';
    },
    //上传封面
    uploadCoverClick(param) {
      const formData = new FormData()
      formData.append('file', param.file) // 传入bpmn文件
      uploadCover(formData).then(res => {
        if (res.code === 200) {
          this.userInfo.coverImg = res.dataMap.url
          meassageSuccess(res.msg)
        } else {
          meassageError(res.msg)
        }
      })
    }
    ,
    //改
    updateObjClick(row) {
      this.userInfo.teacherName = row.videoInstructor//指导老师名称
      this.userInfo.tutorialName = row.tutorialName//作品名称
      this.userInfo.categoryId = row.categoryId
      this.userInfo.subjectId = row.subjectId
      this.userInfo.categoryArr = [row.categoryId.toString(), row.subjectId.toString()]//作品类别
      this.userInfo.tutorialIntroduct = row.tutorialIntroduct//作品内容
      this.userInfo.coverImg = row.coverImg//作品封面
      this.userInfo.fileName = row.tutorialName//视频名称
      this.userInfo.fileVideo = row.tutorialName//视频文件
      this.activeName = 'uploadWorks'
      this.addOrUpdateFlag = false//修改
      console.log("改", this.activeName)
    }
    ,
    //详情
    detailsClick(row) {
      this.showList = false
      this.works = {
        coverImg: row.coverImg,
        tutorialName: row.tutorialName,//作品名称
        nickName: row.nickName,//学生姓名
        videoInstructor: row.videoInstructor,//指导老师
        videoEvaluation: row.videoEvaluation,//评语
        number: row.number,//分数
        tutorialIntroduct: row.tutorialIntroduct,//作品内容
        videoUrl: row.videoUrl,//视频url
        videoScore: row.videoScore
      }
    }
    ,
    rowClick() {
      meassageSuccess(123)
    },
    deleteClick(id) {
      remove({id}).then(res => {
        if (res.code === 200) {
          this.$message.success(res.msg)
          this.getVideoList()
        } else {
          this.$message.error(res.msg)
        }
      })
    }
    ,
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const worksObj = {
            id: this.addOrUpdateFlag ? '' : this.userInfo.id,	             //非必传，不传时为""
            tutorialName: this.userInfo.tutorialName,
            tutorialIntroduct: this.userInfo.tutorialIntroduct,
            videoUrl: this.userInfo.videoUrl,
            categoryId: this.userInfo.categoryId,
            categoryName: this.userInfo.categoryName,
            subjectId: this.userInfo.subjectId,
            subjectName: this.userInfo.subjectName,
            coverImg: this.userInfo.coverImg,
            teacherName: this.userInfo.teacherName
          }
          this.submitLoad = true
          uploadStudentCover(worksObj).then(res => {
            if (res.code === 200) {
              this.userInfo.categoryArr = null//作品类别
              this.userInfo.tutorialName = ''//作品名称
              this.userInfo.tutorialIntroduct = ''//视频内容
              this.userInfo.fileName = ''//文件名称
              this.userInfo.fileVideo = null
              this.userInfo.coverImg = ''
              this.userInfo.teacherName = ''
              meassageSuccess(res.msg)
            } else {
              meassageError(res.msg)
            }
            this.submitLoad = false
          }).catch(error => {
            this.submitLoad = false
          })
        } else {
          return false;
        }

      });
    },
    getDiccName(code) {
      return this.diccArr.filter(r => r.value === code)[0].label
    },
    getVideoList() {
      //获取我的作品列表
      const params = {
        pageSize: 100,
        pageIndex: 1,
        tutorialName: ''
      }
      getVideolListById(params).then(res => {
        if (res.code === 200) {
          const list = res.data.list
          for (let i = 0; i < list.length; i++) {
            const obj = list[i]
            obj.number = obj.videoScore + "分"
            obj.videoScore = (obj.videoScore / 100) * 5
          }
          this.worksList = list
        }
      })
    }
  }
  ,
  mounted() {
    //获取学生基本信息
    getStudentInfo().then(async res => {
      if (res.code === 200) {
        //对象属性拷贝
        Object.assign(this.userInfo, res.data)
        this.userInfo.classesId = res.data.classesName2//班级名称
      }
    })

  }
  ,
  watch: {
    "userInfo.categoryArr"(newValue) {
      if (newValue) {
        this.userInfo.categoryId = newValue[0]
        this.userInfo.categoryName = this.getDiccName(newValue[0])
        this.userInfo.subjectId = newValue[1]
        this.userInfo.subjectName = this.getDiccName(newValue[1])
      }
    },
    activeName(newValue) {
      if (newValue === 'myWorks') {
        this.getVideoList()
        this.addOrUpdateFlag = true//新增
        this.userInfo.teacherName = null//指导老师名称
        this.userInfo.tutorialName = null//作品名称
        this.userInfo.categoryId = null
        this.userInfo.subjectId = null
        this.userInfo.categoryArr = null//作品类别
        this.userInfo.tutorialIntroduct = null//作品内容
        this.userInfo.coverImg = null//作品封面
        this.userInfo.fileName = null//视频名称
        document.title = "双英口语-我的作品"
      } else {
        document.title = "双英口语-上传作品"
      }
      console.log(newValue)
    }
  }

}
</script>

<style scoped>

.heart-box {
  height: 40px;
  line-height: 40px;
}

/deep/ .el-divider--horizontal {
  margin: 0;
}

.margin-left-20 {
  margin-left: 20px
}

.markItem {
  width: 888px;
  height: 148px;
}

.markItem:hover {
  background-color: #F7F9FF;

  .updateBox {
    display: block;
  }
}


.line {
  width: 10px;
  height: 15px;
  border-right: solid #44A6FF 2px;
  margin-right: 2px;
}

/deep/ .el-textarea__inner {
  height: 100px;
}

/deep/ .el-upload--picture-card {
  height: 78px;
  width: 78px;
  line-height: 78px;
}

.textareaBox {
  min-width: 160px;
  width: 430px;
}

@media screen and (max-width: 620px) {
  .textareaBox {
    width: 160px;
  }
}

.el-button-custom {
  color: #333333;
  background: #FFFFFF;
  box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.2);
  opacity: 1;
  border: white;
}

.desc-box {
  height: 180px;
  width: 252px;
  margin-top: 10px;
  background-color: rgb(128, 128, 128);
}

.worksCon {
  font-size: 12px;
  color: #666666;
  margin-top: 30px;
  margin-bottom: 50px;
  background: #FFFFFF;
  border-radius: 5px 5px 5px 5px;
  opacity: 1;
}

.student-teacher {
  font-size: 12px;
  color: #666666;
  margin: 10px 0;
  width: 72px;
  height: 12px;
  font-weight: 400;
  line-height: 12px;
}

.zplb {
  width: 160px;
}

</style>
